<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\service\UploadService;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageOrders;
use plugin\ycMassage\app\model\MassageService;
use plugin\ycMassage\app\model\MassageServiceComment;
use plugin\ycMassage\app\model\MassageShop;
use plugin\ycMassage\app\model\MassageShopComment;
use plugin\ycMassage\app\model\MassageUserTechnician;
use plugin\ycMassage\app\model\MassageUserTechnicianComment;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\OrdersState;
use support\Request;
use think\facade\Db;

class CommentController extends BaseController
{
    protected $noNeedLogin = ["list", "statistics"];
    public function list(Request $request)
    {
        $saas_appid = $request->appid;
        if ($request->saas_appid) {
            $saas_appid = $request->saas_appid;
        }
        $limit = $request->get('limit', 20);
        $page = $request->get('page', 1);
        $id = $request->get('id');
        if (empty($id)) {
            return $this->fail('参数错误');
        }
        $where = [
            'comment.saas_appid' => $saas_appid,
            'comment.show' => State::YES['value'],
            'comment.examine' => Examine::YES['value']
        ];
        $action = $request->get('action');
        switch ($action) {
            case 'technician':
                $where['comment.technician_id'] = $id;
                $model = MassageUserTechnicianComment::alias('comment')->where($where);
                break;
            case 'service':
                $where['comment.service_id'] = $id;
                $model = MassageServiceComment::alias('comment')->where($where);
                break;
            case 'shop':
                $where['comment.shop_id'] = $id;
                $model = MassageShopComment::alias('comment')->where($where);
                break;
            default:
                return $this->fail('参数错误');
        }
        $scene = $request->get('scene');
        switch ($scene) {
            case 'good':
                $model->where('comment.grade', '>=', 4);
                break;
            case 'medium':
                $model->where('comment.grade', '>=', 2)->where('comment.grade', '<=', 3);
                break;
            case 'bad':
                $model->where('comment.grade', '<=', 1);
                break;
        }
        $comment = $model->join('massage_user u', 'u.id=comment.uid')
            ->field('comment.*,u.nickname,u.headimg')
            ->order('comment.create_time desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) use ($saas_appid) {
                if ($item->anony) {
                    $item->nickname = '匿名用户';
                    $item->headimg = UploadService::url(getHpConfig('default_avatar', $saas_appid, 'user'));
                } else {
                    $item->nickname = base64_decode($item->nickname);
                    if (strpos($item->headimg, 'http') !== 0) {
                        $item->headimg = UploadService::url($item->headimg);
                    }
                }
            });
        if ($comment->isEmpty()) {
            return $this->fail('暂无记录');
        }
        return $this->successRes($comment);
    }
    public function statistics(Request $request)
    {
        $saas_appid = $request->appid;
        if ($request->saas_appid) {
            $saas_appid = $request->saas_appid;
        }
        $id = $request->get('id');
        if (empty($id)) {
            return $this->fail('参数错误');
        }
        $where = [
            'saas_appid' => $saas_appid,
            'show' => State::YES['value'],
            'examine' => Examine::YES['value']
        ];
        $action = $request->get('action');
        switch ($action) {
            case 'technician':
                $where['technician_id'] = $id;
                $model = MassageUserTechnicianComment::class;
                break;
            case 'service':
                $where['service_id'] = $id;
                $model = MassageServiceComment::class;
                break;
            case 'shop':
                $where['shop_id'] = $id;
                $model = MassageShopComment::class;
                break;
            default:
                return $this->fail('参数错误');
        }
        $sum = $model::where($where)->count();
        $good = $model::where($where)->where('grade', '>=', 4)->count();
        $medium = $model::where($where)->where('grade', '>=', 2)->where('grade', '<=', 3)->count();
        $bad = $model::where($where)->where('grade', '<=', 1)->count();
        $data = [
            'navList' => [
                [
                    'name' => "全部({$sum})",
                    'scene' => 'all'
                ],
                [
                    'name' => "好评({$good})",
                    'scene' => 'good'
                ],
                [
                    'name' => "中评({$medium})",
                    'scene' => 'medium'
                ],
                [
                    'name' => "差评({$bad})",
                    'scene' => 'bad'
                ]
            ]
        ];
        return $this->successRes($data);
    }
    public function technician(Request $request)
    {
        $limit = $request->get('limit', 20);
        $page = $request->get('page');
        $action = $request->get('action', 'user');
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $where = ['comment.saas_appid' => $saas_appid];
        $modelObj = MassageUserTechnicianComment::alias('comment');
        $field = [
            'comment.*'
        ];
        if ($action == 'user') {
            $where['comment.uid'] = $uid;
            $modelObj->join('massage_user ut', 'ut.id=comment.technician_id');
            $field[] = 'ut.nickname,ut.headimg';
        } else {
            $where['comment.technician_id'] = $uid;
            $modelObj->join('massage_user u', 'u.id=comment.uid');
            $field[] = 'u.nickname,u.headimg';
        }
        $list = $modelObj->where($where)
            ->field($field)
            ->order('comment.id desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                $item->nickname = base64_decode($item->nickname);
                if (strpos($item->headimg, 'http') !== 0) {
                    $item->headimg = UploadService::url($item->headimg);
                }
                $item->reply_content = '';
            });
        if ($list->isEmpty()) {
            return $this->fail('暂无记录');
        }
        return $this->successRes($list);
    }
    public function create(Request $request)
    {
        $D = $request->post();
        $anony = $D['anony'];
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        Db::startTrans();
        try {
            $MassageOrders = MassageOrders::where(['uid' => $uid, 'saas_appid' => $saas_appid, 'trade' => $D['trade'], 'state' => OrdersState::WAIT_COMMENT['value']])->find();
            if (!$MassageOrders) {
                throw new \Exception('订单不存在或状态异常');
            }
            $MassageOrders->state = OrdersState::FINISH['value'];
            $MassageOrders->save();
            # 技师评分
            $MassageUserTechnician = MassageUserTechnician::where(['uid' => $MassageOrders->alias_id, 'saas_appid' => $saas_appid])->find();
            if (!$MassageUserTechnician) {
                throw new \Exception(MassageReplaceIndustryPersonnelName($saas_appid,'技师不存在'));
            }
            $technician_grade = $D['grade'];
            $comment_grade = ($MassageUserTechnician->comment_grade_sum + $technician_grade) / ($MassageUserTechnician->comment_num + 1);
            $MassageUserTechnician->comment_grade = $comment_grade;
            $MassageUserTechnician->comment_num = Db::raw('comment_num+1');
            $MassageUserTechnician->comment_grade_sum = Db::raw('comment_grade_sum+' . $technician_grade);
            $MassageUserTechnician->save();
            $MassageUserTechnicianComment = new MassageUserTechnicianComment;
            $MassageUserTechnicianComment->uid = $uid;
            $MassageUserTechnicianComment->saas_appid = $saas_appid;
            $MassageUserTechnicianComment->technician_id = $MassageOrders->alias_id;
            $MassageUserTechnicianComment->grade = $technician_grade;
            $MassageUserTechnicianComment->content = $D['content'];
            if (!empty($D['images'])) {
                $MassageUserTechnicianComment->images = $D['images'];
            }
            $MassageUserTechnicianComment->anony = $anony;
            $MassageUserTechnicianComment->examine = getHpConfig('comment_examine', $saas_appid, 'technician');
            if (!$MassageUserTechnicianComment->examine) {
                $MassageUserTechnicianComment->examine = Examine::WAIT['value'];
            }
            if (empty($D['content'])) {
                $MassageUserTechnicianComment->show = State::NO['value'];
            }
            $MassageUserTechnicianComment->save();
            # 门店评价
            if (!empty($D['shop_id'])) {
                $MassageShop = MassageShop::where(['id' => $D['shop_id'], 'saas_appid' => $saas_appid])->find();
                if ($MassageShop) {
                    $shop_grade = $D['shop_grade'];
                    $comment_grade = ($MassageShop->comment_grade_sum + $shop_grade) / ($MassageShop->comment_num + 1);
                    $MassageShop->comment_grade = $comment_grade;
                    $MassageShop->comment_num = Db::raw('comment_num+1');
                    $MassageShop->comment_grade_sum = Db::raw('comment_grade_sum+' . $shop_grade);
                    $MassageShop->save();
                    $MassageShopComment = new MassageShopComment();
                    $MassageShopComment->uid = $uid;
                    $MassageShopComment->saas_appid = $saas_appid;
                    $MassageShopComment->mch_id = $MassageShop->mch_id;
                    $MassageShopComment->shop_id = $MassageShop->id;
                    $MassageShopComment->grade = $shop_grade;
                    $MassageShopComment->content = $D['shop_content'];
                    if (!empty($D['shop_images'])) {
                        $MassageUserTechnicianComment->images = $D['shop_images'];
                    }
                    $MassageShopComment->anony = $anony;
                    $MassageShopComment->examine = getHpConfig('comment_examine', $saas_appid, 'shop');
                    if (!$MassageShopComment->examine) {
                        $MassageShopComment->examine = Examine::WAIT['value'];
                    }
                    if (empty($D['shop_content'])) {
                        $MassageShopComment->show = State::NO['value'];
                    }
                    $MassageShopComment->save();
                }
            }
            # 服务评分
            foreach ($D['projects'] as $key => $project) {
                $MassageService = MassageService::where(['id' => $project['service_id'], 'saas_appid' => $saas_appid])->find();
                if ($MassageService) {
                    $grade = $project['grade'];
                    $comment_grade = ($MassageService->comment_grade_sum + $grade) / ($MassageService->comment_num + 1);
                    $MassageService->comment_grade = $comment_grade;
                    $MassageService->comment_num = Db::raw('comment_num+1');
                    $MassageService->comment_grade_sum = Db::raw('comment_grade_sum+' . $grade);
                    $MassageService->save();
                    $MassageServiceComment = new MassageServiceComment();
                    $MassageServiceComment->uid = $uid;
                    $MassageServiceComment->saas_appid = $saas_appid;
                    $MassageServiceComment->service_id = $MassageService->id;
                    $MassageServiceComment->grade = $grade;
                    $MassageServiceComment->content = $project['content'];
                    if (!empty($project['images'])) {
                        $MassageServiceComment->images = $project['images'];
                    }
                    $MassageServiceComment->anony = $anony;
                    $MassageServiceComment->examine = getHpConfig('comment_examine', $saas_appid, 'service');
                    if (!$MassageServiceComment->examine) {
                        $MassageServiceComment->examine = Examine::WAIT['value'];
                    }
                    if (empty($project['content'])) {
                        $MassageServiceComment->show = State::NO['value'];
                    }
                    $MassageServiceComment->save();
                }
            }
            Db::commit();
            return $this->success('评论成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail($th->getMessage());
        }
    }
    public function reply(Request $request)
    {
        $D = $request->post();
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $id = $D['id'];
        $reply_content = $D['reply_content'];
        $comment = MassageUserTechnicianComment::where(['id' => $id, 'saas_appid' => $saas_appid, 'technician_id' => $uid])->find();
        if (!$comment) {
            return $this->fail('评论不存在');
        }
        $comment->reply = $reply_content;
        $comment->examine = getHpConfig('comment_examine', $saas_appid, 'technician');
        if (!$comment->examine) {
            $comment->examine = Examine::WAIT['value'];
        }
        if ($comment->save()) {
            return $this->success('回复成功');
        }
        return $this->fail('回复失败');
    }
}
